import { makeObservable, observable, action, flow, computed } from 'mobx'
import Todo from './Todo'
import axios from 'axios'

export default class TodoStore {
  constructor () {
    this.todos = []
    this.filterCondition = 'All'
    makeObservable(this, {
      todos: observable,
      addTodo: action.bound,
      loadTodos: flow,
      unCompletedTodoCount: computed,
      removeTodo: action.bound,
      filterCondition: observable,
      changeFilterCondition: action.bound,
      filterTodos: computed
    })
    this.loadTodos()
  }
  /* 添加 */
  addTodo (title) {
    this.todos.push(new Todo({ title, id: this.generateTodoId() }))
  }
  generateTodoId () {
    if (this.todos.length === 0) return 1
    return this.todos.reduce((id, todo) => (id < todo.id ? todo.id : id), 0) + 1
  }
  /* 加载远端数据 */
  * loadTodos () {
    let response = yield axios.get('http://localhost:3001/todos')
    response.data.forEach(todo => this.todos.push(new Todo(todo)))
  }
  /* 计算未完成 */
  get unCompletedTodoCount () {
    return this.todos.filter(todo => !todo.isCompleted).length
  }
  /* 删除 */
  removeTodo (id) {
    this.todos = this.todos.filter(todo => todo.id !== id)
  }
  /* 选择过滤条件 */
  changeFilterCondition (condition) {
    this.filterCondition = condition
  }
  /* 根据条件过滤 */
  get filterTodos () {
    switch (this.filterCondition) {
      case 'Active':
        return this.todos.filter(todo => !todo.isCompleted)
      case 'Completed':
        return this.todos.filter(todo => todo.isCompleted)
      default:
        return this.todos
    }
  }
}
